package anji.plus.system.mark.jobs;
import java.text.DecimalFormat;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.ArrayList;
import anji.plus.system.mark.mapper.TaskListMapper;
import anji.plus.system.mark.controller.TaskListController;
import anji.plus.system.mark.response.ResponseResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import anji.plus.system.mark.domain.TaskList;
import anji.plus.system.mark.domain.TaskNodeList;
import anji.plus.system.mark.dto.RankInfo;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.time.LocalDate;
import javax.annotation.Resource;



@Component
public class ScheduleTask {

    @Resource
    private TaskListMapper taskListMapper;

    //    @Scheduled(cron = "0 0/3 * * * *") //定时任务注解+cron表达式  -每天凌晨1点执行
    @Scheduled(cron = "0 0 1 1/1 * *") //定时任务注解+cron表达式  -每天凌晨1点执行
    public void testScheduleTask() {
        LocalDate currentDate = LocalDate.now();
        System.out.println("***开始执行 任务到期超时更新***");
        taskListMapper.jobsUpdateExpiredTask(currentDate);
    }

    //查工时
    public Double queryUserScheduleTime(String name, LocalDate monthFirstDate, LocalDate nextMonthfirstday) {
        Double qTimeNum = 0.00;
        qTimeNum = taskListMapper.queryUserScheduleTime(name, monthFirstDate, nextMonthfirstday);
        return qTimeNum;
    }

    //查用户得分
    public Double queryUserScore(String name, LocalDate monthFirstDate, LocalDate nextMonthfirstday) {
        Integer qTaskNum = taskListMapper.queryUserTaskNum(name, monthFirstDate, nextMonthfirstday);
        Double qScore = 0.00;

        if (qTaskNum == null) {
            qTaskNum = 0;
            qScore = 0.00;
        } else if (qTaskNum == 0) {
            qScore = 0.00;
        } else if (qTaskNum <= 4) {
            int t1 = 0;
            List<Double> nodeScoreList = new ArrayList<>();
            nodeScoreList = taskListMapper.queryUserAllScore(name, monthFirstDate, nextMonthfirstday);
            t1 = nodeScoreList.size();
            qScore = 25 * t1 * (taskListMapper.queryUserScore(name, monthFirstDate, nextMonthfirstday)) / 100;
        } else {
            qScore = taskListMapper.queryUserScore(name, monthFirstDate, nextMonthfirstday);
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String f1 = df.format(qScore);
        return Double.valueOf(f1);
    }

    //查用户数
    public Integer queryUserTaskNum(String name, LocalDate monthFirstDate, LocalDate nextMonthfirstday) {
        Integer qTaskNum = taskListMapper.queryUserTaskNum(name, monthFirstDate, nextMonthfirstday);
        if (qTaskNum == null) {
            qTaskNum = 0;
        }
        return qTaskNum;
    }


    private String queryUserTaskNumIsEnough(String element, LocalDate monthFirstDay, LocalDate nextMonthfirstday) {
        String  t1 = taskListMapper.queryUserTaskNumIsEnough(element, monthFirstDay, nextMonthfirstday);
        String taskNumIsEnough;
        int a1 = Integer.parseInt(t1);
        if (a1 < 3) {
            taskNumIsEnough = "0";
        }else{
            taskNumIsEnough = "1";
        }
        return taskNumIsEnough;
    }


    public List<RankInfo> userScoreRank2(LocalDate monthFirstDay, LocalDate nextMonthfirstday) {
        //list 是接口，不是实体类
        List<RankInfo> lr = new ArrayList<>();
        List<String> list1 = Arrays.asList("陈建明", "周冲", "高晓龙", "来青原", "李辉", "刘津津", "卢威", "孟令雪", "彭旭峰",
                "尤优","刘综南","肖泽文"
        );
        List<String> list2 = Arrays.asList(
                "陈中伟", "李杰", "倪敬伟", "阮思哲", "孙书怡", "王琳", "杨光鹏", "周骏"
        );

        if (1 == 1){
            for (String element : list1) {
                RankInfo rankInfo = new RankInfo();
                rankInfo.setUserName(element);
                rankInfo.setTaskTimeNum(queryUserScheduleTime(element,monthFirstDay,nextMonthfirstday));
                rankInfo.setTaskCount(queryUserTaskNum(element, monthFirstDay, nextMonthfirstday));
                rankInfo.setTaskScore(Double.valueOf(queryUserScore(element, monthFirstDay, nextMonthfirstday)));
                rankInfo.setTaskNumIsEnough(queryUserTaskNumIsEnough(element, monthFirstDay, nextMonthfirstday));
                lr.add(rankInfo);
            }
            System.out.println("***********************************");
            lr.forEach(item -> System.out.println(item));
            System.out.println("***********************************");
//        lr.sort(Comparator.comparing(RankInfo::getTaskScore).reversed().thenComparing(RankInfo::getTaskCount).reversed().thenComparing(RankInfo::getUserName).reversed());
//        lr.sort(Comparator.comparingDouble(RankInfo::getTaskScore).thenComparingInt(RankInfo::getTaskCount).reversed().thenComparing(RankInfo::getUserName));
//            按分数，任务数 倒叙排序
//            lr.sort(Comparator.comparingDouble(RankInfo::getTaskScore).thenComparingInt(RankInfo::getTaskCount).reversed());
//          按分数，任务数，工时 倒叙排序
            lr.sort(Comparator.comparingDouble(RankInfo::getTaskScore).thenComparingInt(RankInfo::getTaskCount).thenComparingDouble(RankInfo::getTaskTimeNum).reversed());
            lr.forEach(item -> System.out.println(item));
            System.out.println("***********************************");
            return lr;
        } else{
            for (String element : list2) {
                RankInfo rankInfo = new RankInfo();
                rankInfo.setUserName(element);
                rankInfo.setTaskCount(queryUserTaskNum(element, monthFirstDay, nextMonthfirstday));
                rankInfo.setTaskScore(Double.valueOf(queryUserScore(element, monthFirstDay, nextMonthfirstday)));
                lr.add(rankInfo);
            }
            System.out.println("***********************************");
            lr.forEach(item -> System.out.println(item));
            System.out.println("***********************************");
//        lr.sort(Comparator.comparing(RankInfo::getTaskScore).reversed().thenComparing(RankInfo::getTaskCount).reversed().thenComparing(RankInfo::getUserName).reversed());
//        lr.sort(Comparator.comparingDouble(RankInfo::getTaskScore).thenComparingInt(RankInfo::getTaskCount).reversed().thenComparing(RankInfo::getUserName));
            lr.sort(Comparator.comparingDouble(RankInfo::getTaskScore).thenComparingInt(RankInfo::getTaskCount).reversed());
            lr.forEach(item -> System.out.println(item));
            System.out.println("***********************************");
            return lr;
        }
    }


    @Scheduled(cron = "0 0 1 1 * ?") //定时任务注解+cron表达式  -每天凌晨1点执行
    public void rangeList() {
        LocalDate currentDate = LocalDate.now();
        // 获取年份和月份
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();

        if(month == 1){
            month = 12;
            year = year-1;
        }else{
            month = month-1;
        }
        System.out.println(currentDate);
        System.out.println("***开始执行 月初发放上月奖励转盘抽奖资格***");

        LocalDate monthFirstDay = LocalDate.of(Integer.parseInt(String.valueOf(year)), Integer.parseInt(String.valueOf(month)), 1);
        //当月第一天
//        System.out.println(monthFirstDay);
        // 获取指定日期的最后一天
        LocalDate lastDayOfMonth = monthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate nextMonthfirstday = lastDayOfMonth.plusDays(1);
        //次月第一天
//        System.out.println(nextMonthfirstday);
        List<RankInfo> lr1 = userScoreRank2(monthFirstDay,nextMonthfirstday);
        // 获取前3个元素
        List<RankInfo> firstThree = lr1.subList(0, Math.min(lr1.size(), 3));
        System.out.println("前3个元素: " + firstThree);
        for (RankInfo rankInfo : firstThree) {
            String userName = rankInfo.getUserName();
            taskListMapper.updatePrize(userName);
        }
        //添加抽奖资格-奖励
        // 获取后3个元素
        List<RankInfo> lastThree = lr1.subList(Math.max(lr1.size() - 3, 0), lr1.size());
        System.out.println("后3个元素: " + lastThree);
        //添加抽奖资格-惩罚
        for (RankInfo rankInfo : lastThree) {
            String userName = rankInfo.getUserName();
            taskListMapper.updatePunish(userName);
        }

    }
}
////周冲： 测试代码，尝试使用：
////        Cron表达式参数参考：https://www.matools.com/cron/    在线Cron表达式生成器
////        秒（0~59） 例如0/5表示每5秒
////        分（0~59）
////        时（0~23）
////        日（0~31）的某天，需计算
////        月（0~11）
////        周几（ 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT）